"""
Configuration Manager using python-dotenv
========================================

This module provides a centralized way to manage environment variables
using python-dotenv library.
"""

import os
from dotenv import load_dotenv
from pathlib import Path

class ConfigManager:
    """Configuration manager for the application"""
    
    def __init__(self, env_file=None):
        """
        Initialize the configuration manager
        
        Args:
            env_file (str): Path to the .env file. If None, will look for .env in current directory
        """
        self.env_file = env_file or '.env'
        self._load_env()
    
    def _load_env(self):
        """Load environment variables from .env file"""
        env_path = Path(self.env_file)
        
        if env_path.exists():
            load_dotenv(env_path)
            print(f"✅ Loaded environment variables from {self.env_file}")
        else:
            print(f"⚠️  Warning: {self.env_file} not found. Using system environment variables.")
    
    def get(self, key, default=None):
        """
        Get an environment variable
        
        Args:
            key (str): Environment variable name
            default: Default value if not found
            
        Returns:
            str: Environment variable value
        """
        return os.getenv(key, default)
    
    def get_longport_config(self):
        """
        Get LongPort API configuration
        
        Returns:
            dict: LongPort configuration
        """
        return {
            'app_key': self.get('LONGPORT_APP_KEY'),
            'app_secret': self.get('LONGPORT_APP_SECRET'),
            'access_token': self.get('LONGPORT_ACCESS_TOKEN')
        }
    
    def validate_longport_config(self):
        """
        Validate that all LongPort configuration is present
        
        Returns:
            bool: True if all required config is present
        """
        config = self.get_longport_config()
        required_keys = ['app_key', 'app_secret', 'access_token']
        
        missing_keys = [key for key in required_keys if not config.get(key)]
        
        if missing_keys:
            print(f"❌ Missing LongPort configuration: {missing_keys}")
            return False
        
        print("✅ LongPort configuration validated successfully")
        return True
    
    def create_env_file(self, config_dict):
        """
        Create a .env file with the provided configuration
        
        Args:
            config_dict (dict): Configuration dictionary
        """
        env_content = []
        
        for key, value in config_dict.items():
            env_content.append(f"{key}={value}")
        
        with open(self.env_file, 'w') as f:
            f.write('\n'.join(env_content))
        
        print(f"✅ Created {self.env_file} with configuration")
    
    def update_env_file(self, updates):
        """
        Update specific environment variables in .env file
        
        Args:
            updates (dict): Dictionary of key-value pairs to update
        """
        # Read existing .env file
        env_vars = {}
        if os.path.exists(self.env_file):
            with open(self.env_file, 'r') as f:
                for line in f:
                    line = line.strip()
                    if line and not line.startswith('#') and '=' in line:
                        key, value = line.split('=', 1)
                        env_vars[key] = value
        
        # Update with new values
        env_vars.update(updates)
        
        # Write back to file
        with open(self.env_file, 'w') as f:
            for key, value in env_vars.items():
                f.write(f"{key}={value}\n")
        
        print(f"✅ Updated {self.env_file} with new configuration")
    
    def reload_env(self):
        """Reload environment variables from .env file"""
        self._load_env()


def setup_longport_env():
    """
    Setup LongPort environment variables
    
    This function creates a .env file with LongPort configuration
    """
    config_manager = ConfigManager()
    
    # LongPort configuration
    longport_config = {
        'LONGPORT_APP_KEY': 'b05c383f70f49c5affd8aa959bd55da0',
        'LONGPORT_APP_SECRET': '0eb1a4dfce6a5d4a2b07e451e32fbf27bb11bb23ef1484b21d244eb265bcc882',
        'LONGPORT_ACCESS_TOKEN': 'm_eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJsb25nYnJpZGdlIiwic3ViIjoiYWNjZXNzX3Rva2VuIiwiZXhwIjoxNzYyMzU3MDA2LCJpYXQiOjE3NTQ1ODEwMDUsImFrIjoiYjA1YzM4M2Y3MGY0OWM1YWZmZDhhYTk1OWJkNTVkYTAiLCJhYWlkIjoyMDQ5OTUwOSwiYWMiOiJsYiIsIm1pZCI6MTYwMTIwMTgsInNpZCI6Ijl3ZjhtQStOMFhCNjg0cWZMdjdyY0E9PSIsImJsIjozLCJ1bCI6MCwiaWsiOiJsYl8yMDQ5OTUwOSJ9.HmaXknJ3Teo1n3nLL01dnDaBQNJeoIgKU4zg1cuejkfRVLxA4ISh2RYmwa6W3BPLaHs5CNaFJ4O-RVDlTGwuR9Ps7vQj81pf6Zo3UDWQs06EbkyWeY6PhBJw8YJOsZr-pgrgVuUG4GIWQtAuoDwYp8kUr8pq3_jGZSHQra_Xv2AsOtfbiihsUE9S2clc9sB6hJeckcOKDSArHSOH8HasiTEEjghnKcqGQH_evZaG4yYw3DaxFB-chxJ6AikatkdNEIaAPH0gg5R7a0TmCGz5zYTkB1lXEQ1zhY76MmS8vKOHEue776JneopVWXGtbc3Ww9v8eEwV0WDTp4MQvvoJMRDpMJ6nfIPTqNJKscH3s5y8VT7-Uf8i62kwmBP0BCdkwREMGTCFPHBGO606Z3WlQdnXpd2sTHAfyXHUkpJyEGUOfgrdP7IVvy1eFWD07KFGNtbkcVS5YyMtWSQHAATyms34f-t7updL4aWlUI0KKVuMeR9L--JJxJPNi14zfq8OMwk4BDBcpGF7zlzJRHmsnFcVPYHX8FKHBq5m9e8L5dxJqI5CRrVH2A4hto-eJOtNGbtXp42dRsS3ZgdrXWfAOmPH8cx9CTOAUeJuL_RZ6vETvpCvxIMnfbVXGpXo5wgXnHpWY_by2egBo0Umf607Y67jBtXqYJZYJQmZhUen0Ik'
    }
    
    config_manager.create_env_file(longport_config)
    return config_manager


if __name__ == "__main__":
    # Test the configuration manager
    print("Testing Configuration Manager...")
    
    # Setup LongPort environment
    config_manager = setup_longport_env()
    
    # Validate configuration
    if config_manager.validate_longport_config():
        print("✅ Configuration setup completed successfully!")
    else:
        print("❌ Configuration validation failed!")
